﻿package controllers.myinfo;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import rbac.models.Oplog;
import rbac.models.PrivilegeType;
import rbac.models.User;
import utils.DateUtil;
import utils.NumberUtil;
import utils.PinyingUtil;

import models.Demandinfo;
import models.Estate2;
import models.Estate2history;
import models.Proofrinfo;
import models.Stzd;

import java.io.Serializable;  
import java.lang.reflect.Field;  
import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;  

import com.et.ar.annotations.Column;
import com.et.mvc.BinaryView;
import com.et.mvc.JsonView;
import com.et.mvc.JspView;
import com.et.mvc.MultipartFile;
import com.et.mvc.TextView;
import com.et.mvc.View;

import com.et.mvc.filter.BeforeFilter;
import com.et.mvc.filter.BeforeFilters;

import controllers.ApplicationController;


public class EsinfoController extends ApplicationController {
	
	public void index() throws Exception{
    	
	}
	
	public View getStzd(String ids) throws Exception{
		List<Stzd> lists = Stzd.findAll(Stzd.class, " py like '%" + ids + "%' ", null, "id desc", 25);
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		for(Stzd item: lists){
			Map<String,Object> child = new HashMap<String,Object>();
			child.put("text", item.getDz());
			result.add(child);
		}
		return new JsonView(result);		
	}
	
	public JspView showEstateInfo(int id,String local_id) throws Exception {
		User user = (User) rbac.getCurrentUser();	
		Estate2 item = null;
		if ((local_id != null) && (!local_id.equals("")))
		{
			item = Estate2.findFirst(Estate2.class,"local_id = ? and (" +  
				"display = 0 or display = 1 "+  //无限制 和  只在中介的
"or (z_id in (select Company_ID from ZJList where Company_ID in ("+
" select mainid from ZJList where Company_ID = ?"+  //同个总公司的
"))) or z_id = ?)",new Object[]{local_id,user.getDepartment().getCompany_id(),user.getDepartment().getCompany_id()});
		}
        if (item == null){
        	item = Estate2.findFirst(Estate2.class,"id = ? and (" +  
    				"display = 0 or display = 1 "+  //无限制 和  只在中介的
    "or (z_id in (select Company_ID from ZJList where Company_ID in ("+
    " select mainid from ZJList where Company_ID = ?"+  //同个总公司的
    "))) or z_id = ?)",new Object[]{id,user.getDepartment().getCompany_id(),user.getDepartment().getCompany_id()});
        }
		
        JspView view = new JspView("/read/esinfo/showEstateInfo.jsp"); 
        view.setAttribute("item", item);
        view.setAttribute("rm", "norm");
        return view;
	}
	
	public View getEstate2Items(int page, int rows, String q,int t, String sort, String order) throws Exception {
		User user = (User) rbac.getCurrentUser();		
		String orderBy = "editdate desc";
		if (sort != null && order != null){
			orderBy = sort + " " + order;
		}
		String cond = "1=1";
		List<Object> tmpArgs = new ArrayList<Object>();
		
		/**
		if (t != 0){
			cond += " and (parentId = ?)";
			tmpArgs.add(t);
		}

		**/
		if (q != null){
			cond += " and (address like '%"+q+"%' or mode like '%"+q+"%' ) ";			
		}
		
		if (!isAdmin())
            cond += " and z_id = '" + user.getDepartment().getCompany_id() +"'";

		Object[] args = tmpArgs.toArray();
		
		long total = Estate2.count(Estate2.class, cond, args);
		List<Estate2> items = Estate2.findAll(Estate2.class, cond, args, orderBy, rows, (page-1)*rows);
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("total", total);
		result.put("rows", items);
		
		return new JsonView(result);
	}
	
	private String getLocal_id(int deptid) throws Exception{
		String dpid = "000000"+ String.valueOf(deptid);
		dpid = dpid.substring(dpid.length()-6, dpid.length());
		String localid = "000001";
		Estate2 estate2 = Estate2.findFirst(Estate2.class," Local_ID like '"+dpid+"%' and len(Local_ID) = 12",null,"Local_ID desc");
		if (estate2 != null){
		  localid = estate2.getLocal_id().substring(6, 12);
		  localid = "000000" + String.valueOf(Integer.parseInt(localid) + 1);
		  localid = localid.substring(localid.length()-6, localid.length());
		}		
		localid = dpid + localid;
		return localid;
	}
	
	private String  getItemErrorMsg(Estate2 item,User user) throws Exception {
		String msg = "";
		
		//置顶和在网上的数量是否超过每天设置
		String todayDate = DateUtil.formatter("yyyy-MM-dd 00:00:01",DateUtil.getNowDate().getTime());
		long l = Estate2.count(Estate2.class, "editdate >='"+todayDate+"' and z_id = ? and totop = 1 and flag ='0'", new Object[]{  user.getDepartment().getCompany_id() });
		if (l >= user.getDepartment().getTopcount()){
			msg += "今天网站置顶记录数已满("+user.getDepartment().getTopcount()+")！";
		}
		
		l = Estate2.count(Estate2.class, "editdate >='"+todayDate+"' and z_id = ? and toweb = 1 and flag ='0'", new Object[]{  user.getDepartment().getCompany_id() });
		if (l >= user.getDepartment().getWebcount()){
			msg += "今天网站首页显示记录数已满("+user.getDepartment().getWebcount()+")！";
		}
		
		if ((item.getMode() == null) || (item.getMode().equals(""))){
			msg += "没有选择方式！";
		}
		
		if ((item.getPurpose() == null) || (item.getPurpose().equals(""))){
			msg += "没有选择类别！";
		}
		
		if ((item.getMap() == null) || (item.getMap().equals(""))){
			msg += "没有选择区域！n";
		}
		
		if ((item.getAddress() == null) || (item.getAddress().equals(""))){
			msg += "没有填写位置！";
		}
		
		if ((item.getLayer() == null) || (item.getLayer().equals(""))){
			msg += "没有选择楼层！";
		}
		
		if ((item.getFitment() == null) || (item.getFitment().equals(""))){
			msg += "没有选择装修！";
		}
		
		if ((item.getArea() == null) || (item.getArea() <= 0 )){
			msg += "没有面积！";
		}
		
		if ((item.getPrice() == null) || (item.getPrice() <= 0 )){
			msg += "没有价格！";
		}
		
		if ((item.getUnit() == null) || (item.getUnit().equals(""))){
			msg += "没有选择价格单位！";
		}
		
		if (item.getMode().equals("出售")){
			if ((item.getCircs() == null) || (item.getCircs().equals(""))){
				msg += "没有选择手续！";
			}
			
			if ((!item.getUnit().equals("元/m2")) && (!item.getUnit().equals("万元/套"))
					&& (!item.getUnit().equals("面议")) && (!item.getUnit().equals("亩")) ){
						msg += "选择方式为[出售]，不能选择单位为["+item.getUnit()+"]";
					}
			
		}else{
			if ((!item.getUnit().equals("元/月")) && (!item.getUnit().equals("元/月/m2"))
			&& (!item.getUnit().equals("面议")) && (!item.getUnit().equals("亩")) ){
				msg += "选择方式为[出租]，不能选择单位为["+item.getUnit()+"]";
			}
			
		}
		
		
		return msg;
	}
	
	
	private Float getTotalPricef(Estate2 item) {
		
	  float i = 1;
	  Float totalprice = 0f;
	  
	  
	  if ((item.getUnit().equals("元/月/m2")) || (item.getUnit().equals("元/m2")) ||
	    (item.getUnit().equals("亩")))
	  {
		  if (item.getUnit().equals("亩")) i = 666.667f;
		  
		  totalprice = item.getArea() * item.getPrice() / i; 
		  
	  }else{
		  if (item.getUnit().equals("万元/套")) 
				  {
			  totalprice = item.getPrice() * 10000;
				  }else{
					  totalprice = item.getPrice();
				  }
		     
	  }
	    
		return (float)(Math.round((totalprice / i)*100))/100;
	}
	
	// 该方法实现对对象的拷贝操作
    public static Estate2history copy(Estate2history objectCopy,Estate2 object) throws Exception
    {
    	objectCopy.setAddress(object.getAddress());
    	objectCopy.setArea(object.getArea());
    	objectCopy.setCircs(object.getCircs());
    	objectCopy.setCity(object.getCity());
    	objectCopy.setDatenumber(object.getDatenumber());
    	objectCopy.setDetail_add(object.getDetail_add());
    	objectCopy.setDirection(object.getDirection());
    	objectCopy.setDisplay(object.getDisplay());
    	objectCopy.setDt_pos(object.getDt_pos());
    	objectCopy.setEditdate(object.getEditdate());
    	objectCopy.setExtra_memo(object.getExtra_memo());
    	objectCopy.setFitment(object.getFitment());
    	objectCopy.setFlag(object.getFlag());
    	objectCopy.setFullpyaddress(object.getFullpyaddress());
    	objectCopy.setFzrf(object.getFzrf());
    	objectCopy.setImage_count(object.getImage_count());
    	
    	objectCopy.setInputdate(object.getInputdate());
    	objectCopy.setLocal_id(object.getLocal_id());
    	objectCopy.setWeb_id(object.getWeb_id());
    	objectCopy.setSelfcode(object.getSelfcode());
    	
    	objectCopy.setMode(object.getMode());
    	objectCopy.setRegion(object.getRegion());
    	objectCopy.setName(object.getName());
    	
    	objectCopy.setPyaddress(object.getPyaddress());
    	objectCopy.setPurpose(object.getPurpose());
    	objectCopy.setLayer(object.getLayer());
    	
    	objectCopy.setRoom(object.getRoom());
    	objectCopy.setPrice(object.getPrice());
    	objectCopy.setUnit(object.getUnit());
    	objectCopy.setTotalprice(object.getTotalprice());
    	objectCopy.setScheduled_flag(object.getScheduled_flag());
    	objectCopy.setMemo(object.getMemo());
    	objectCopy.setZ_id(object.getZ_id());
    	objectCopy.setUnitname(object.getUnitname());
    	objectCopy.setOper(object.getOper());
    	objectCopy.setTotop(object.getTotop());
    	objectCopy.setToweb(object.getToweb());
    	objectCopy.setMap(object.getMap());
    	objectCopy.setWg(object.getWg());
    	objectCopy.setQt(object.getQt());
    	objectCopy.setSj(object.getSj());
    	objectCopy.setUsr_op_type(object.getUsr_op_type());
    	objectCopy.setPhone_flag(object.getPhone_flag());
    	objectCopy.setVideo_count(object.getVideo_count());
        
        return objectCopy;
    }
    
	public View saveEstate2(Estate2 item, String[] rids) throws Exception {
		Map<String,Object> result = new HashMap<String,Object>();
		
		User user = (User) rbac.getCurrentUser();
		//取得中介的id，再补全6位，再取得 6+6 的最大值，再加1
		item.setLocal_id(getLocal_id(user.getDepartmentid()));
		if ((item.getCity()==null) || (item.getCity().equals(""))) item.setCity("汕头市");
		item.setName(item.getAddress());
		item.setUsr_op_type("新增");
		item.setPyaddress(PinyingUtil.getHeadByStrings(item.getAddress()));
		item.setFullpyaddress(PinyingUtil.hanziToPinyin(item.getAddress()));
		item.setDetail_add(item.getAddress());
		item.setFlag("0");
		item.setOper(user.getLogin());
		item.setTotalprice(getTotalPricef(item));
		item.setInputdate(new java.sql.Timestamp(System
				.currentTimeMillis()));
		item.setEditdate(new java.sql.Timestamp(System
				.currentTimeMillis()));
		item.setZ_id(user.getDepartment().getCompany_id());
		item.setUnitname(user.getDepartment().getSxname());
		
		String msg = "";
		
		msg = getItemErrorMsg(item,user);
		
		if (msg == ""){
		if (item.save()){
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")新增房源信息，内容为：" + new JsonView(item));									

			result.put("success", true);
		} else {
			result.put("failure", true);
			result.put("msg", getErrorMsg(item));
		}
		}else{
			result.put("failure", true);
			result.put("msg", msg);
		} 
		
		View view = new JsonView(result);
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}
	
	public View updateEstate2(int id, Map<String,Object> params, String[] rids) throws Exception {
		Map<String,Object> result = new HashMap<String,Object>();
		Estate2 item = Estate2.find(Estate2.class, id);
		JsonView olditem= new JsonView(item);
		item = Estate2.updateModel(item, params);
		User user = (User) rbac.getCurrentUser();
		
		if ((item.getCity()==null) || (item.getCity().equals(""))) item.setCity("汕头市");
		item.setName(item.getAddress());
		item.setUsr_op_type("修改");
		item.setPyaddress(PinyingUtil.getHeadByStrings(item.getAddress()));
		item.setFullpyaddress(PinyingUtil.hanziToPinyin(item.getAddress()));
		item.setDetail_add(item.getAddress());
		item.setFlag("0");
		
		item.setOper(user.getLogin());
		item.setTotalprice(getTotalPricef(item));
		item.setEditdate(new java.sql.Timestamp(System
				.currentTimeMillis()));
		item.setZ_id(user.getDepartment().getCompany_id());
		item.setUnitname(user.getDepartment().getSxname());
		if ((isAdmin()) || (item.getOper().equals(user.getLogin())))
		{
			
			String msg = "";
			
			msg = getItemErrorMsg(item,user);
			
			if (msg == ""){
				//当月历史库是否有一条，没有，先增加一条到历史库中
				String todayDate = DateUtil.formatter("yyyy-MM-01 00:00:01",DateUtil.getNowDate().getTime());
				long l = Estate2history.count(Estate2history.class, "editdate >='"+todayDate+"' and local_id = ?", new Object[]{ item.getLocal_id() });
				if (l == 0)
				{
					Estate2history history = new Estate2history();
					copy(history,item);					
					history.save();
				}
				
			if (item.save()){
				Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")修改房源信息，原内容为："+ olditem + "\r\n修改内容为：" + new JsonView(item));										

				result.put("success", true);
			} else {
				result.put("failure", true);
				result.put("msg", getErrorMsg(item));
			}
			}else{
				result.put("failure", true);
				result.put("msg", msg);
			} 
		}else{
			result.put("failure", true);
			result.put("msg", "你没有权限操作这条记录。");			
		}
		
		View view = new JsonView(result);
		view.setContentType("text/plain;charset=utf-8");
		return view;
	}
	
	public View destroyEstate2(int id) throws Exception {
		Estate2 item = Estate2.find(Estate2.class, id);
		User user = (User) rbac.getCurrentUser();
		if ((isAdmin()) || (item.getOper().equals(user.getLogin())))
		{
			Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")删除房源信息，内容为：" + new JsonView(item));									

			item.setUsr_op_type("删除");
			item.setFlag("-1");
    		item.save();
    		String todayDate = DateUtil.formatter("yyyy-MM-01 00:00:01",DateUtil.getNowDate().getTime());
			long l = Estate2history.count(Estate2history.class, "editdate >='"+todayDate+"' and local_id = ?", new Object[]{ item.getLocal_id() });
			if (l == 0)
			{
				Estate2history history = new Estate2history();
				copy(history,item);					
				history.save();
			}
		}
		return new JsonView("success:true");
	}
	
	public View batdestroyEstate2(String ids) throws Exception {
		User user = (User) rbac.getCurrentUser();
        if ((ids!=null) && (NumberUtil.isNumbers(ids)))
		{
        	Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")批量删除房源信息，编号为：" + ids);									

        	Estate2.execute(Estate2.class,"update Estate2 set editdate = getdate(),usr_op_type='删除',flag='-1'  where  z_id = ? and id in (" +ids+ ") ", new Object[]{  user.getDepartment().getCompany_id() });
		}
		return new JsonView("success:true");
	}
	
	public View updateDateEstate2(String ids) throws Exception {
		
        User user = (User) rbac.getCurrentUser();
        if ((ids!=null) && (NumberUtil.isNumbers(ids)))
		{
        	
        	Oplog.addMsg(user.getLogin(), user.getName() + "("+getIpAddr(request)+")批量更新房源信息时间，编号为：" + ids);									

            Estate2.execute(Estate2.class,"update Estate2 set editdate = getdate(),usr_op_type='提前',flag='0'  where  z_id = ? and id in (" +ids+ ") ", new Object[]{  user.getDepartment().getCompany_id() });
            
          //这里还要防止，将多日前的置顶，在首页更新过来，超过总数的，只设置最新的条数
    		String todayDate = DateUtil.formatter("yyyy-MM-dd 00:00:01",DateUtil.getNowDate().getTime());
    		long l = Estate2.count(Estate2.class, "editdate >='"+todayDate+"' and z_id = ? and totop = 1 and flag ='0'", new Object[]{  user.getDepartment().getCompany_id() });
    		if (l >= user.getDepartment().getTopcount()){
    			Estate2.execute(Estate2.class,"update Estate2 set totop = 0  where  z_id = ?  and totop = 1 and flag ='0' and id not in ( select top 20 id from Estate2 where  z_id = ? and totop = 1 and flag ='0' order by editdate desc ) ", new Object[]{  user.getDepartment().getCompany_id() ,user.getDepartment().getCompany_id() });
                
    		}
    		
    		l = Estate2.count(Estate2.class, "editdate >='"+todayDate+"' and z_id = ? and toweb = 1 and flag ='0'",  new Object[]{  user.getDepartment().getCompany_id() });
    		if (l >= user.getDepartment().getWebcount()){
    			Estate2.execute(Estate2.class,"update Estate2 set toweb = 0  where  z_id = ? and toweb = 1 and flag ='0' and id not in ( select top 20 id from Estate2 where  z_id = ? and toweb = 1 and flag ='0' order by editdate desc ) ", new Object[]{  user.getDepartment().getCompany_id() ,user.getDepartment().getCompany_id() });
                
    		}
		}
		
		return new JsonView("success:true");
	}
	
}
